//
//  CZUserAcount.swift
//  WeiBoNew
//
//  Created by 秦川 on 16/5/12.
//  Copyright © 2016年 秦川. All rights reserved.
//

import UIKit

class CZUserAcount: NSObject, NSCoding {
    
    var access_token: String?
    var expires_in: NSTimeInterval = 0 {
        didSet{
        expiresDate = NSDate().dateByAddingTimeInterval(expires_in)
    
        }
    }
    
    var expiresDate: NSDate?
    
    var uid: Int64 = 0
    var name: String?
    var avatar_large: String?
    
    //  kvc 构造函数

    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
     //  防止不崩溃
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
      //  重写description属性
    override var description: String{
    let keys = ["access_token", "expires_in", "uid", "name", "avatar_large"]
    
    return dictionaryWithValuesForKeys(keys).description
    }
    
    //  MARK:     --归档和解档
    //  归档
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
        
    }
     //  解档
  required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
    expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
    uid = aDecoder.decodeInt64ForKey("uid")
    name = aDecoder.decodeObjectForKey("name") as? String
    avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    func saveUserAccount() -> Bool{
    let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archiver")
        
    return NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    class func loadUserAccount() -> CZUserAcount? {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archiver")
        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? CZUserAcount
    }
}
